//
//  AppDelegate+WXApi.m
//  tingche
//
//  Created by 尤振宇 on 2017/6/8.
//  Copyright © 2017年 尤振宇. All rights reserved.
//

#import "AppDelegate+WXApi.h"
#import <AFNetworking.h>
#import "MBProgressHUD+Category.h"

@implementation AppDelegate (WXApi)

-(void)registerWX
{
    [WXApi registerApp:WXAPPID];
}

-(BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options
{
    return [WXApi handleOpenURL:url delegate:self];
}

-(BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
    return [WXApi handleOpenURL:url delegate:self];
}

-(void)onResp:(BaseResp *)resp
{
    if ([resp isKindOfClass:[SendAuthResp class]]) {   //授权登录的类。
        if (resp.errCode == 0) {
            SendAuthResp *resp2 = (SendAuthResp *)resp;
            [self request:resp2.code];
        }else if (resp.errCode == -2){
            [MBProgressHUD showError:@"用户已取消"];
        }
    }
}


-(void)request:(NSString *)code
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];//请求
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];//响应
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html",@"application/json", @"text/json",@"text/plain", nil];
    //通过 appid  secret 认证code . 来发送获取 access_token的请求
    [manager GET:[NSString stringWithFormat:@"https://api.weixin.qq.com/sns/oauth2/access_token?appid=%@&secret=%@&code=%@&grant_type=authorization_code",WXAPPID,WXAPPSECRET,code] parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {  //获得access_token，然后根据access_token获取用户信息请求。
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];

        NSString *accessToken = [dic valueForKey:@"access_token"];
        NSString *openID = [dic valueForKey:@"openid"];

        [manager GET:[NSString stringWithFormat:@"https://api.weixin.qq.com/sns/userinfo?access_token=%@&openid=%@",accessToken,openID] parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSDictionary *dic = (NSDictionary *)[NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            
            [[NSNotificationCenter defaultCenter]postNotificationName:kWeChatLoginSuccessfully object:dic];
            
//       dic = {
//                city = "";
//                country = "";
//                headimgurl = "http://wx.qlogo.cn/mmopen/5xkeUt7Rm34Qj5Q9OkXGibOgzog568yAucCCB976TNvNceCxPgo0MhwyanEBnFxQQKgQpbJ59Wpm1Rh9yCp7BDpZIJOLd6nCc/0";
//                language = "zh_CN";
//                nickname = "\U5c24\U632f\U5b87";
//                openid = "owPmE0QK9gaVfEwcS6J5e_dpXoHg";
//                privilege =     (
//                );
//                province = "";
//                sex = 1;
//                unionid = oqi1MwpCORqUnDAzRYIfgtH5XntU;
//            }
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {

        }];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}

@end
